<?php

namespace App\Services\AuthUser;

use App\Models\User;
use GuzzleHttp\Client;

class AuthUser
{
	protected $realName;
	
	protected $identifyNum;
	
	
	public function __construct($realName, $identifyNum)
	{
		$this->realName = $realName;
		$this->identifyNum = $identifyNum;
		$this->user = request()->user();
	}

	protected function getGuzzleClient()
	{
		return new Client(['Content-Type' => 'application/x-www-form-urlencoded']);
	}
	
	
	protected function verifyUser()
	{
		$identifyCount = User::query()->where("identify_num",$this->identifyNum)->count();
		if($identifyCount >= 1){
			fail("您的实名认证已达上限");
		}

		$year = substr($this->identifyNum, 6, 4);

		if($year > 2006){

			fail("未到18岁无法认证！");
		}

		if($year < 1959){

			fail("超过65岁无法认证！");
		}

		return true;
	}
	
	protected function authUser()
	{
		/*$host = env('SJB_AUTH_URL');

		$param = array(
			'name' => $this->realName,
			'idcard' => $this->identifyNum,
		);
		// 接⼝序列号，在"第⼆步"中获取
		$param['key'] =  env('SJB_AUTH_KEY');;

		$result = $this->getGuzzleClient()
				->post($host, ['query' => $param])->getBody()->getContents();


		var_dump($result);die;*/

		$host = "https://safrv.market.alicloudapi.com";
	    $path = "/id_name_verify";
	   	/*$host = "http://id2meta.market.alicloudapi.com";
	    $path = "/id2meta";*/
	    $method = "POST";
	    $appcode = env('AUTH_APP_CODE');
	    $headers = array();
	    array_push($headers, "Authorization:APPCODE " . $appcode);
	    $userName = rawurlencode($this->realName);
	    $querys = "identifyNum=".$this->identifyNum."&userName=".$userName;
	    $bodys = "";
	    $url = $host . $path . "?" . $querys;
	  
	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
	    curl_setopt($curl, CURLOPT_URL,$url);
	    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	    curl_setopt($curl, CURLOPT_FAILONERROR, false);
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($curl, CURLOPT_HEADER, true);
	    if (1 == strpos("$".$host, "https://"))
	    {
	        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	    }
	    $result =curl_exec($curl);
		$result = explode("\r\n",$result);
		$result = array_pop($result);
		$result = json_decode($result,true);
		
		if($result['code']==200 && $result['data']['bizCode']==1){
			$this->user->update(['auth_real_name'=>$this->realName,'identify_num'=>$this->identifyNum]);

		}else{

			fail('实名认证验证失败');
		}		
		/*return User::create([
			'grade' => 'vip',
			'name' => $this->name,
			'phone' => $this->phone,
			'password' => bcrypt($this->password),
			'avatar' => $avatar,
		]);*/
	}
	
	public function auth()
	{
		$this->verifyUser();
		
		
		$this->authUser();

		return true;
	}
}
